import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { config } from "process";

class Request {
  // request实例
  instance: AxiosInstance;

  // 传入配置对象初始化
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);

    // 全局拦截器
    // this.instance.interceptors.request.use((reqConf: AxiosRequestConfig) => {
    //   return config;
    // });
  }

  // request函数
  request<T>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<T, AxiosResponse<T>>(config)
        .then((res) => resolve(res.data))
        .catch((err) => {
          reject(err);
          return err;
        });
    });
  }
  // get请求
  get<T>(url: string, params?: any, headers?: any): Promise<T> {
    return this.request({ url, params, headers, method: "GET" });
  }
  // post请求
  post<T>(url: string, data?: any, headers?: any): Promise<T> {
    return this.request({ url, data, headers, method: "POST" });
  }
}

export default Request;
